package 临时工具;

import java.nio.charset.StandardCharsets;

public class HexShiftSwapEncryptor {


    // 加密
    public static String encrypt(String input) {
        byte[] bytes = input.getBytes(StandardCharsets.UTF_8);
        StringBuilder result = new StringBuilder();
        for (int i = 0; i <bytes.length ; i++) {
            byte b= bytes[i];
            int shifted = (b & 0xFF) - i%16;
            if (shifted < 0) {
                shifted += 256;
            }
            String hex = String.format("%02X", shifted); // 两位十六进制
            String swapped = swapHexDigits(hex);
            result.append(swapped);
        }


        return swapHexDigits(result.toString());

    }
    // 解密
    public static String decrypt(String encryptedHex) {
        encryptedHex=swapHexDigits(encryptedHex);
        int len = encryptedHex.length();
        byte[] bytes = new byte[len / 2];

        for (int i = 0; i < len; i += 2) {
            // 取出加密后的Hex值并反转
            String swappedHex = encryptedHex.substring(i, i + 2);
            String originalHex = swapHexDigits(swappedHex);

            // 转为十六进制整数
            int value = Integer.parseInt(originalHex, 16);

            // 恢复原始字节（加上索引的偏移量）
            value = (value + (i / 2) % 16) % 256;
            bytes[i / 2] = (byte) value;
        }

        // 将字节数组转换回原始字符串
        return new String(bytes, StandardCharsets.UTF_8);
    }

    // 工具方法：交换两个十六进制字符的位置，例如 "9A" → "A9"
    private static String swapHexDigits(String hex) {
        return new StringBuilder(hex).reverse().toString();
    }

    public static void main(String[] args) {
        String original = "你好,123 Hello123!";
        String encrypted = encrypt(original);
        String decrypted = decrypt(encrypted);

        System.out.println("原文: " + original);
        System.out.println("加密后的十六进制: " + encrypted);
        System.out.println("解密还原: " + decrypted);
    }
}
